﻿<%@ WebHandler Language="C#" Class="DownloadHandler" %>

using System;
using System.Web;
using System.IO;

public class DownloadHandler : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        String fileName = context.Request.QueryString["filename"]; //客户端保存的文件名
        String filePath = context.Server.MapPath("~/" + fileName); //路径

        FileInfo fileInfo = new FileInfo(filePath);
        if (fileInfo.Exists)
        {
            byte[] buffer = new byte[102400];
            context.Response.Clear();

            FileStream iStream = File.OpenRead(filePath);
            long dataLengthToRead = iStream.Length; //获取下载的文件总大小

            context.Response.ContentType = "application/octet-stream";
            context.Response.AddHeader("Content-Disposition", "attachment;  filename=" +
                               HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
            while (dataLengthToRead > 0 && context.Response.IsClientConnected)
            {
                int lengthRead = iStream.Read(buffer, 0, Convert.ToInt32(102400));//'读取的大小

                context.Response.OutputStream.Write(buffer, 0, lengthRead);
                context.Response.Flush();
                dataLengthToRead = dataLengthToRead - lengthRead;
            }
            context.Response.Close();
            context.Response.End();
        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}